const { app, BrowserWindow, desktopCapturer, session } = require('electron')


let mainWin = null
const createWindow = () => {
  mainWin = new BrowserWindow({
    width: 1000,
    height: 800,
    title: '自定义菜单',
    webPreferences: {
      // 允许渲染进程使用nodejs
      nodeIntegration: true,
      // 允许渲染进程使用nodejs
      contextIsolation: false,
    }
  })

  session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
    desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
      // Grant access to the first screen found.
      console.log(sources)
      callback({ video: sources[0], audio: "loopback" })
    })
  })

  mainWin.loadURL('https://hkmeeting.schkzy.com/')
  mainWin.webContents.openDevTools()
  mainWin.webContents.on('did-finish-load', () => {
    // 页面加载完成后注入脚本
    injectScript();
  });
}
function injectScript() {
  const script = `
    (function() {
      // 创建按钮
      const openCamera = document.createElement('button');
      openCamera.id = 'openCamera';
      openCamera.textContent = '打开摄像头';
      openCamera.style.backgroundColor = 'transparent'; // 设置背景颜色为透明
      openCamera.style.color = 'white'; // 设置字体颜色为白色
      openCamera.style.border = 'none'; // 移除边框

      const screenRecord = document.createElement('button');
      screenRecord.id = 'screenRecord';
      screenRecord.textContent = '屏幕录制';
      screenRecord.style.backgroundColor = 'transparent';
      screenRecord.style.color = 'white';
      screenRecord.style.border = 'none';

      const start = document.createElement('button');
      start.id = 'start';
      start.textContent = '开始录制';
      start.style.backgroundColor = 'transparent';
      start.style.color = 'white';
      start.style.border = 'none';

      const stop = document.createElement('button');
      stop.id = 'stop';
      stop.textContent = '停止录制';
      stop.style.backgroundColor = 'transparent';
      stop.style.color = 'white';
      stop.style.border = 'none';

      const play = document.createElement('button');
      play.id = 'play';
      play.textContent = '播放录制的视频';
      play.style.backgroundColor = 'transparent';
      play.style.color = 'white';
      play.style.border = 'none';

      const save = document.createElement('button');
      save.id = 'save';
      save.textContent = '保存录制的视频';
      save.style.backgroundColor = 'transparent';
      save.style.color = 'white';
      save.style.border = 'none';

      // 创建视频元素
      const originVideo = document.createElement('video');
      originVideo.id = 'originVideo';
      

      const playVideo = document.createElement('video');
      playVideo.id = 'playVideo';
      playVideo.width = 400;
      playVideo.height = 500;
      const container = document.createElement('div');
      container.id = 'recordingControls';
      container.style.position = 'fixed';
      container.style.top = '10px';
      container.style.right = '10px';
      container.style.zIndex = '9999';
      container.appendChild(openCamera);
      container.appendChild(screenRecord);
      container.appendChild(start);
      container.appendChild(stop);
      container.appendChild(play);
      container.appendChild(save);
      container.appendChild(originVideo);
      container.appendChild(playVideo);
      document.body.appendChild(container);

      let systemStream;
      let audioStream;
      let blobData = [];
      let recordInstance;
      let mergedStream;

      // 打开摄像头
      openCamera.addEventListener("click", () => {
        handleOpenCamera();
      });

      // 屏幕录制
      screenRecord.addEventListener("click", () => {
        handleScreenRecord();
      });

      // 开始录制
      start.addEventListener("click", () => {
        startRecord();
      });

      // 停止录制
      stop.addEventListener("click", () => {
        recordInstance && recordInstance.stop();
        blobData = [];
      });

      // 播放录制的视频
      play.addEventListener("click", () => {
        const blob = new Blob(blobData, { type: 'video/mp4' });
        const videoUrl = URL.createObjectURL(blob);
        playVideo.src = videoUrl;
        playVideo.play();
      });

      save.addEventListener("click", () => {
        if (blobData.length > 0) {
          const blob = new Blob(blobData, { type: 'video/mp4' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = 'recording.mp4'; // 设置下载文件名
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url); // 释放对象URL
          document.body.removeChild(a);
        } else {
          console.error('No recorded data available.');
        }
      });

      // 打开摄像头
      const handleOpenCamera = async () => {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            width: 400, height: 500
          },
          audio: true
        });
        getAudioStream();
        console.log("handleOpenCamera stream", stream);
        originVideo.srcObject = stream;
        originVideo.play();
      };

      // 屏幕录制
      const handleScreenRecord = async () => {
        systemStream = await navigator.mediaDevices.getDisplayMedia({
          video: {
            width: 1920, height: 1080
          },
          audio: {
            echoCancellation: true,
            noiseSuppression: true
          }
        });
        console.log("handlescreenRecord stream", systemStream);
        getAudioStream();
      };

      function getAudioStream() {
        navigator.mediaDevices.getUserMedia({ audio: true, video: false })
          .then(function (stream) {
            audioStream = stream;
            console.log('Micro audio started.', audioStream);
            mergeStreams(); // 合并音频流
            stream.onended = () => {
              console.log('Micro audio ended.');
            };
          })
          .catch(function (error) {
            console.error('getUserMedia() failed:', error);
          });
      }

      function mergeStreams() {
        if (systemStream && audioStream) {
          mergedStream = new MediaStream();
          const audioContext = new AudioContext();
          const dest = audioContext.createMediaStreamDestination();
          audioStream.getAudioTracks().forEach((track) => {
            const source = audioContext.createMediaStreamSource(
              new MediaStream([track])
            );
            source.connect(dest);
          });
          systemStream.getAudioTracks().forEach((track) => {
            const source = audioContext.createMediaStreamSource(
              new MediaStream([track])
            );
            source.connect(dest);
          });
          dest.stream.getTracks().forEach((track) => mergedStream.addTrack(track));
          audioStream.getTracks().forEach((track) => mergedStream.addTrack(track));
          systemStream.getTracks().forEach((track) => mergedStream.addTrack(track));
          console.log('Streams merged.', mergedStream);
        } else {
          console.error('Both streams are not available to merge.');
        }
      }

      // 开始录制
      const startRecord = () => {
        recordInstance = new MediaRecorder(mergedStream, { mimeType: 'video/webm' });
        console.log("startRecord stream", mergedStream);
        if (recordInstance) {
          recordInstance.start();
          recordInstance.ondataavailable = function (e) {
            blobData.push(e.data);
          };
          recordInstance.onstop = function (e) {
            console.log("startRecord onstop");
          };
        }
      };
    })();
  `;

  mainWin.webContents.executeJavaScript(script);
}
app.whenReady().then(() => {
  createWindow()
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})


